package P130_CountDownLatch;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author xufy
 * @version 1.0
 * @description CountDownLatch 协调子线程
 **/
public class CountDownLatchThread {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int num = 10;
        CountDownLatch begin = new CountDownLatch(1);
        CountDownLatch end = new CountDownLatch(num);
        ExecutorService es = Executors.newFixedThreadPool(num);
        List<Future<Integer>> funtures = new ArrayList<Future<Integer>>();
        for (int i = 0; i < num; i++) {
            funtures.add(es.submit(new Runner(begin, end)));
        }
        //开始，主线程是begin的计数器为0
        begin.countDown();
        //等待所有结束
        end.await();
        int count = 0;
        for (Future<Integer> f : funtures) {
            count += f.get();
        }
        System.out.println("平均分数为：" + count / num);
    }

}

class Runner implements Callable<Integer> {
    private CountDownLatch begin;
    private CountDownLatch end;

    public Runner(CountDownLatch _begin, CountDownLatch _end) {
        begin = _begin;
        end = _end;
    }

    @Override
    public Integer call() throws Exception {
        int score = new Random().nextInt(25);
        begin.await();
        TimeUnit.MILLISECONDS.sleep(score);
        end.countDown();
        return score;
    }
}